package com.atguigu.msmservice.utils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * @author He Wentao
 * @since 2022/9/18 11:31
 */

public class RandomUtil {
    private static final Random random = new Random();

    private static final DecimalFormat fourFormat = new DecimalFormat("0000");

    private static final DecimalFormat sixFormat = new DecimalFormat("000000");

    /**
     *  获取 4 位随机数
     * @return 随机数字符串
     */
    public static String getFourBitRandom() {
        return fourFormat.format(random.nextInt(10000));
    }

    /**
     * 获取 6 位随机数
      * @return 随机数字符串
     */
    public static String getSixBitRandom(){
        return sixFormat.format(random.nextInt(1000000));
    }

    /**
     * 从给定 list 数组中，随机抽取 n 个元素
     * @param list 存放总元素的容器
     * @param n 要抽取的元素个数
     * @return 返回随机抽取的元素
     */
    public static ArrayList<?> getRandom(List<Integer> list,int n){
        Random random = new Random();

        HashMap<Object,Object> hashMap = new HashMap<>();

        // 生成随机数，并存入 hashMap 
        for (int i = 0; i < list.size(); i++) {
            int number = random.nextInt(100)+1;
            hashMap.put(number,i);
        }

        // 从 HashMap 导入数组
        Object [] randomObject = hashMap.values().toArray();

        ArrayList<Integer> r = new ArrayList<>();

        // 遍历数组并打印数据
        for (int i = 0; i < n; i++) {
            r.add(list.get((int) randomObject[i]));
            System.out.println(list.get((int) randomObject[i])+"\t");
        }
        System.out.println("\n");

        return r;
    }
}
